using System.Linq;
using UnityEngine;
using System.Collections;


public class WormHole : MonoBehaviour
{
    public GameController gameController;
    public Animator animator;
    // 生成时的时间，用于防止虫洞重叠，让后生成的避开
    public float creationTime;
    // 传送CD
    public float teleportCooldown = 3f;
    // 计时
    private float teleportTimer = 0f;
    // 是否准备好传送
    public bool isTeleportReady = false;
    public bool isTeleportReadyForBug = false;
    // 传送CD
    public float teleportCooldownForBug = 3f;
    // 计时
    private float teleportTimerForBug = 0f;
    private float borderTop;
    private float borderBottom;
    private float borderLeft;
    private float borderRight;
    [Header("存在时间")]
    public float ExistTimeMin = 10;
    public float ExistTimeMax = 20;
    private float existTime = 15;
    private float existTimer = 0;
    public Player player;
    void Start()
    {
        StartCoroutine(StartPlaySound(1f));
        gameController = GameObject.Find("GameController").GetComponent<GameController>();
        borderTop = gameController.BattlefieldBorderTop;
        borderBottom = gameController.BattlefieldBorderBottom;
        borderLeft = gameController.BattlefieldBorderLeft;
        borderRight = gameController.BattlefieldBorderRight;

        existTime = Random.Range(ExistTimeMin, ExistTimeMax);


        // 随机一个位置生成
        transform.position = new Vector3(Random.Range(borderLeft, borderRight), Random.Range(borderBottom, borderTop), 0);
        // 防止虫洞重叠


        // 如果只有这一个虫洞
        if (GameObject.FindGameObjectsWithTag("Wormhole").Length <= 1)
        {
            // 再生成一个虫洞
            Instantiate(this.gameObject);
        }
    }

    void Update()
    {
        SummonWormholeTimer();
        TryToDestory();
    }

    private IEnumerator StartPlaySound (float delay)
    {
        yield return new WaitForSeconds(delay);
        AudioManager.Instance.PlaySFX(6);

    }

    // 触发传送，进入CD计时
    public void TriggerTeleport(Collider2D other)
    {
        if (other.CompareTag("Player") && isTeleportReadyForBug)
        {
            if (player.IsDashing || player.IsFlying) return;
            isTeleportReadyForBug = false;
            teleportTimerForBug = 0f;
        }
        if (other.CompareTag("Enemy") && isTeleportReady)
        {
            isTeleportReady = false;
            teleportTimer = 0f;
        }
    }

    // 触发器进入
    void OnTriggerEnter2D(Collider2D other)
    {
        // 防止生成重叠
        if (other.CompareTag("Wormhole"))
        {
            if (creationTime > other.GetComponent<WormHole>().creationTime)
            {
                Instantiate(this.gameObject);
                Destroy(this.gameObject);
            }
        }
        if (other.CompareTag("Enemy"))
        {
            if (!isTeleportReady) return;
            // 传送玩家到另一个虫洞
            WormHole[] wormholes = GameObject.FindGameObjectsWithTag("Wormhole").Select(w => w.GetComponent<WormHole>()).Where(w => w.isTeleportReady && w != this).ToArray();
            if (wormholes.Length == 0) return; // 只有一个虫洞 不传送
            WormHole targetWormhole = wormholes[Random.Range(0, wormholes.Length)];
            targetWormhole.TriggerTeleport(other); // 重置目标虫洞传送状态
            TriggerTeleport(other); // 重置自身传送状态
            StartCoroutine(Teleport(targetWormhole, other));
        }
        if (other.CompareTag("Player"))
        {
            if (!isTeleportReadyForBug) return;
            // 传送玩家到另一个虫洞
            WormHole[] wormholes = GameObject.FindGameObjectsWithTag("Wormhole").Select(w => w.GetComponent<WormHole>()).Where(w => w.isTeleportReadyForBug && w != this).ToArray();
            if (wormholes.Length == 0) return; // 只有一个虫洞 不传送
            WormHole targetWormhole = wormholes[Random.Range(0, wormholes.Length)];
            targetWormhole.TriggerTeleport(other); // 重置目标虫洞传送状态
            TriggerTeleport(other); // 重置自身传送状态
            StartCoroutine(Teleport(targetWormhole, other));
        }
        // if (other.CompareTag("Player"))
        // {
        //     // 传送玩家到另一个虫洞
        //     WormHole[] wormholes = GameObject.FindGameObjectsWithTag("Wormhole").Select(w => w.GetComponent<WormHole>()).ToArray();
        //     if (wormholes.Length <= 1) return; // 只有一个虫洞 不传送
        //     WormHole targetWormhole = null;
        //     foreach (WormHole wh in wormholes)
        //     {
        //         if (wh != this && (wh.isTeleportReady || wh.isTeleportReadyForBug))
        //         {
        //             wh.TriggerTeleport(other); // 重置目标虫洞传送状态
        //             TriggerTeleport(other); // 重置自身传送状态
        //             targetWormhole = wh;
        //             break;
        //         }
        //     }
        //     if (targetWormhole != null)
        //     {
        //         StartCoroutine(Teleport(targetWormhole, other));
        //     }
        // }
    }

    private void SummonWormholeTimer()
    {
        existTimer += Time.deltaTime;
        teleportTimer += Time.deltaTime;
        teleportTimerForBug += Time.deltaTime;
        if (teleportTimer >= teleportCooldown)
        {
            isTeleportReady = true;
            // transform.Find("CD1").gameObject.SetActive(true);
            // transform.Find("CD0").gameObject.SetActive(false);
        }
        else
        {
            isTeleportReady = false;
            // transform.Find("CD1").gameObject.SetActive(false);
            // transform.Find("CD0").gameObject.SetActive(true);
        }
        if (teleportTimerForBug >= teleportCooldownForBug)
        {
            isTeleportReadyForBug = true;
            // transform.Find("CD1").gameObject.SetActive(true);
            // transform.Find("CD0").gameObject.SetActive(false);
        }
        else
        {
            isTeleportReadyForBug = false;
            // transform.Find("CD1").gameObject.SetActive(false);
            // transform.Find("CD0").gameObject.SetActive(true);
        }
    }

    public IEnumerator Teleport(WormHole targetWormhole, Collider2D other)
    {
        yield return new WaitForSeconds(0.2f);
        Debug.Log("传送到虫洞位置: " + targetWormhole.transform.position);
        other.transform.position = targetWormhole.transform.position;
    }
    
    public void TryToDestory()
    {
        if (existTimer >= existTime)
        {
            Destroy(gameObject, 1f);
            animator.SetTrigger("Die");
        }
    }
}